package gov.fnal.mcginnis.threetone;


/**
 * @author mcginnis
 *
 */
public class ColorMatch extends SimplexOptimize
{
	protected int inumColors;
	protected int[] colors = null;
	protected double[] mix = null;
	protected int itargetColor;
	protected int imatchColor;
	
	/**
	 * @param itargetColor
	 * @param inumColors
	 * @param colors
	 */
	public ColorMatch(int itargetColor, int inumColors, int[] colors)
	{
		this.itargetColor = itargetColor;
		this.inumColors = inumColors;
		this.colors  = new int[inumColors];
		this.mix = new double[inumColors];
		for (int ii = 0; ii <  inumColors; ++ii)
		{
			this.colors[ii] = colors[ii];
		}
	}
	@Override
	double fChiSquare() 
	{
		double dsum = 0.0;
		mix[0] = m_variable[0].fvalue;
		dsum = mix[0];
		for (int ii = 1; ii <  m_inum_total_variables; ++ii)
		{
			if ((dsum + m_variable[ii].fvalue) < 1.0)
			{
				mix[ii] = m_variable[ii].fvalue;
			}
			else
			{
				mix[ii] = 1.0 - dsum;
			}
			dsum = dsum + mix[ii];
		}
		mix[m_inum_total_variables] = 1.0 - dsum;
		imatchColor = ColorBox.addColors(inumColors, colors, mix);
		return ColorBox.compareColors(itargetColor, imatchColor);
	}

	@Override
	void setupOptimization() 
	{
		m_inum_total_variables = inumColors - 1; // need the last variable to add up to 100%
		m_inum_opt_variables   = m_inum_total_variables;
		m_variable = new COptimizeVariable[m_inum_total_variables];
		m_ilookup = new int[m_inum_total_variables];

		for (int ii = 0; ii <  m_inum_total_variables; ++ii)
		{
			m_variable[ii] = new COptimizeVariable();
			m_variable[ii].finit_value = 1.0 / ((double) inumColors);
			m_variable[ii].fmin        = 0.0;
			m_variable[ii].fmax        = 1.0;
			m_variable[ii].fstep       = 0.005;
			m_variable[ii].fvalue      = 1.0 / ((double) inumColors);
			m_ilookup[ii] = ii;
		}
		
		m_FwriteAmoebaText = null;
		/* Iterations */
//		m_iopt_limit_type = 1;
	/* Time       */
	/*	m_iopt_limit_type = 2;
	/* Chi Square */
	/*	m_iopt_limit_type = 3; */

		m_iopt_limit_type = 2;
		m_fsim_limit = 1000.0;
		
		return;
	}

}
